package com.bw.springboot.starter.upload.service;

import com.bw.springboot.starter.upload.util.FileProperties;
import com.bw.springboot.starter.upload.util.FileResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Slf4j
public class FileService {

    private FileProperties properties;

    //构造方法传入属性配置
    public FileService(FileProperties fileProperties) {
        this.properties = fileProperties;
        log.info("FileService 实例化....");
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    public FileResult upload(MultipartFile file) throws IOException {
        //文件原名
        String originalFilename = file.getOriginalFilename();
        //文件扩展名称
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."),originalFilename.length());
        //保存的文件名称
        String fileName = UUID.randomUUID()+extName;
        //文件夹是否存在
        File dir = new File(properties.getPath());
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //保存文件
        File saveFile = new File(properties.getPath()+fileName);
        file.transferTo(saveFile);
        //返回结果
        FileResult fileResult = new FileResult();
        fileResult.setDomain(properties.getDomain());
        fileResult.setFileName(fileName);
        fileResult.setFileUrl(properties.getDomain()+fileName);
        return fileResult;
    }

    /**
     * 批量上传
     * @param files
     * @return
     * @throws IOException
     */
    public List<FileResult> uploadBatch(MultipartFile[] files) throws IOException {
        List<FileResult> results = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            FileResult upload = upload(files[i]);
            results.add(upload);
        }
        return results;
    }


}
